package com.kgis.kp.common.vo;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import com.kgis.kp.common.util.Detect;
import com.kgis.kp.common.util.JsonUtil;

/**
 * 
 * @author zhxiaomiao
 * 
 */
public class Ordering implements Serializable {

	/**
	 *
	 */
	private static final long serialVersionUID = -2089909380622627429L;

	public static final String ASC = "ASC";

	public static final String DESC = "DESC";

	/**
	 * Order by LENGTH(NAME), NAME please move to DataAccessObjectConst
	 */
	// @Deprecated
	// public static final Ordering Ordering_NameLengthAndName = new
	// Ordering(Model.FUNCTION_LENGTH + Model.LEFT_PARENTHESIS +
	// Model.Column_NAME + Model.RIGHT_PARENTHESIS).addAsc(Model.Column_NAME);
	private String name;

	private String type = ASC;

	private List<String> orders;

	public Ordering() {

	}

	public Ordering(String _name) {
		this.setName(_name);
	}

	public Ordering(String _name, String _type) {
		this.setName(_name);
		this.setType(_type);
	}

	public Ordering addAsc(String _name) {
		this.add(_name, ASC);
		return this;
	}

	public Ordering addDesc(String _name) {
		this.add(_name, DESC);
		return this;
	}

	private Ordering add(String _name, String _type) {
		if (null == orders) {
			orders = new ArrayList<String>();
		}
		orders.add(_name + " " + _type);
		return this;
	}

	public String orderClause() {
		if (Detect.notEmpty(name) || null != orders) {
			StringBuffer sb = new StringBuffer();

			if (Detect.notEmpty(name)) {
				sb.append(name.toUpperCase()).append(" ").append(type);
			}
			if (null != orders) {
				if (Detect.notEmpty(name)) {
					sb.append(",");
				}
				for (int i = 0; i < orders.size(); i++) {
					if (i > 0) {
						sb.append(",");
					}
					sb.append(orders.get(i));
				}
			}
			return sb.toString();
		}
		return null;
	}

	/**
	 * @return Returns the name.
	 */
	public String getName() {
		return name;
	}

	/**
	 * @param name
	 *            The name to set.
	 */
	public void setName(String name) {
		this.name = name;
	}

	/**
	 * @return Returns the type.
	 */
	public String getType() {
		return type;
	}

	/**
	 * @param type
	 *            The type to set.
	 */
	public void setType(String type) {
		this.type = type;
	}

	public String toString() {
		return JsonUtil.marshal(this);
	}
}
